﻿
package extremefx.tools {
	/**
	 * @author Marcelo Volmaro
	 */
	public class Inflector {
		
		private static var _plurals : Array = [
			[/$/, 's'],
			[/s$/i, 's'],
			[/(ax|test)is$/i, '$1es'],
			[/(octop|vir)us$/i, '$1i'],
			[/(alias|status)$/i, '$1es'],
			[/(bu)s$/i, '$1ses'],
			[/(buffal|tomat)o$/i, '$1oes'],
			[/([ti])um$/i, '$1a'],
			[/sis$/i, 'ses'],
			[/(?:([^f])fe|([lr])f)$/i, '$1$2ves'],
			[/(hive)$/i, '$1s'],
			[/([^aeiouy]|qu)y$/i, '$1ies'],
			[/(x|ch|ss|sh)$/i, '$1es'],
			[/(matr|vert|ind)ix|ex$/i, '$1ices'],
			[/([m|l])ouse$/i, '$1ice'],
			[/^(ox)$/i, '$1en'],
			[/(quiz)$/i, '$1zes']	
		];
		
		private static var _singulars : Array = [
			[/s$/i, ''],
			[/(n)ews$/i, '$1ews'],
			[/([ti])a$/i, '$1um'],
			[/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, '$1$2sis'],
			[/(^analy)ses$/i, '$1sis'],
			[/([^f])ves$/i, '$1fe'],
			[/(hive)s$/i, '$1'],
			[/(tive)s$/i, '$1'],
			[/([lr])ves$/i, '$1f'],
			[/([^aeiouy]|qu)ies$/i, '$1y'],
			[/(s)eries$/i, '$1eries'],
			[/(m)ovies$/i, '$1ovie'],
			[/(x|ch|ss|sh)es$/i, '$1'],
			[/([m|l])ice$/i, '$1ouse'],
			[/(bus)es$/i, '$1'],
			[/(o)es$/i, '$1'],
			[/(shoe)s$/i, '$1'],
			[/(cris|ax|test)es$/i, '$1is'],
			[/(octop|vir)i$/i, '$1us'],
			[/(alias|status)es$/i, '$1'],
			[/^(ox)en/i, '$1'],
			[/(vert|ind)ices$/i, '$1ex'],
			[/(matr)ices$/i, '$1ix'],
			[/(quiz)zes$/i, '$1']			
		];
		
		private static var _irregulars : Vector.<Vector.<String>> = Vector.<Vector.<String>>([
			Vector.<String>(['person', 'people']),
			Vector.<String>(['man', 'men']),
			Vector.<String>(['child', 'children']),
			Vector.<String>(['sex', 'sexes']),
			Vector.<String>(['move', 'moves'])	
		]);		
		
		private static var _uncountable : Vector.<String> = Vector.<String>([
			'equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep'
		]);
		
		public static function pluralize (singular : String) : String {
			if (_uncountable.indexOf(singular) != -1) return singular;
				
			var plural:String = "";
			var p:String;
			
			for each (var item:Array in _plurals) {
				p = singular.replace(item[0], item[1]);
				if (p != singular) plural = p;
			}
			
			return plural;
		}
		
		public static function singularize (plural : String) : String {
			
			if (_uncountable.indexOf(plural) != -1) return plural;
			
			var singular:String = "";
			var s:String;
			for each (var item:Array in _singulars) {
				s = plural.replace(item[0], item[1]);
				if (s != plural) singular = s;
			}
			
			return singular;
		}
		
		static private function _init():void {
			for each (var irr:Vector.<String> in _irregulars) {
				_plurals[_plurals.length] = [irr[0], irr[1]];
				_singulars[_singulars.length] = [irr[1], irr[0]];
			}
		}
		
		_init();
	}
}
